const { Op } = require('sequelize');
const { User, Order, PointsTransaction, Invitation, sequelize } = require('../models');
const pointsService = require('./pointsService');
const logger = require('../utils/logger');

class UserManagementService {
  /**
   * 获取用户列表
   */
  async getUserList(options = {}) {
    try {
      const {
        page = 1,
        limit = 20,
        search,
        status,
        memberLevel,
        startDate,
        endDate,
        sortBy = 'createdAt',
        sortOrder = 'DESC'
      } = options;

      const where = {};
      
      // 搜索条件
      if (search) {
        where[Op.or] = [
          { phone: { [Op.like]: `%${search}%` } },
          { nickname: { [Op.like]: `%${search}%` } },
          { invitationCode: { [Op.like]: `%${search}%` } }
        ];
      }

      // 状态筛选
      if (status !== undefined) {
        where.status = parseInt(status);
      }

      // 会员等级筛选
      if (memberLevel) {
        where.memberLevel = memberLevel;
      }

      // 日期范围筛选
      if (startDate || endDate) {
        where.createdAt = {};
        if (startDate) {
          where.createdAt[Op.gte] = new Date(startDate);
        }
        if (endDate) {
          where.createdAt[Op.lte] = new Date(endDate);
        }
      }

      // 排序
      const orderClause = [[sortBy, sortOrder.toUpperCase()]];

      const { count, rows } = await User.findAndCountAll({
        where,
        attributes: { exclude: ['password'] },
        include: [
          {
            model: User,
            as: 'inviter',
            attributes: ['id', 'nickname', 'phone']
          }
        ],
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit),
        order: orderClause
      });

      // 为每个用户添加统计信息
      const usersWithStats = await Promise.all(rows.map(async (user) => {
        const stats = await this.getUserStatistics(user.id);
        return {
          ...user.toJSON(),
          stats
        };
      }));

      return {
        users: usersWithStats,
        pagination: {
          current: parseInt(page),
          total: Math.ceil(count / limit),
          pageSize: parseInt(limit),
          totalItems: count
        }
      };
    } catch (error) {
      logger.error('Get user list failed:', error);
      throw error;
    }
  }

  /**
   * 获取用户详情
   */
  async getUserById(userId) {
    try {
      const user = await User.findByPk(userId, {
        attributes: { exclude: ['password'] },
        include: [
          {
            model: User,
            as: 'inviter',
            attributes: ['id', 'nickname', 'phone', 'avatar']
          },
          {
            model: User,
            as: 'invitees',
            attributes: ['id', 'nickname', 'phone', 'avatar', 'createdAt']
          }
        ]
      });

      if (!user) {
        throw new Error('用户不存在');
      }

      // 获取用户统计信息
      const stats = await this.getUserStatistics(userId);

      // 获取最近的积分记录
      const recentPointsRecords = await PointsTransaction.findAll({
        where: { userId },
        limit: 10,
        order: [['createdAt', 'DESC']]
      });

      // 获取最近的订单
      const recentOrders = await Order.findAll({
        where: { userId },
        limit: 5,
        order: [['createdAt', 'DESC']]
      });

      return {
        user: user.toJSON(),
        stats,
        recentPointsRecords,
        recentOrders
      };
    } catch (error) {
      logger.error('Get user by id failed:', error);
      throw error;
    }
  }

  /**
   * 获取用户统计信息
   */
  async getUserStatistics(userId) {
    try {
      const [
        orderCount,
        totalSpent,
        pointsEarned,
        pointsSpent,
        inviteCount
      ] = await Promise.all([
        Order.count({ where: { userId } }),
        Order.sum('finalAmount', { where: { userId, status: 'completed' } }) || 0,
        PointsTransaction.sum('amount', { where: { userId, type: 'earn' } }) || 0,
        PointsTransaction.sum('amount', { where: { userId, type: 'spend' } }) || 0,
        User.count({ where: { inviterId: userId } })
      ]);

      return {
        orderCount,
        totalSpent,
        pointsEarned,
        pointsSpent: Math.abs(pointsSpent),
        inviteCount
      };
    } catch (error) {
      logger.error('Get user statistics failed:', error);
      throw error;
    }
  }

  /**
   * 更新用户信息
   */
  async updateUser(userId, updateData, operatorId) {
    try {
      const user = await User.findByPk(userId);
      
      if (!user) {
        throw new Error('用户不存在');
      }

      const { nickname, phone, status, memberLevel, avatar, gender } = updateData;

      // 检查手机号是否已被其他用户使用
      if (phone && phone !== user.phone) {
        const existingUser = await User.findOne({
          where: { 
            phone,
            id: { [Op.ne]: userId }
          }
        });

        if (existingUser) {
          throw new Error('手机号已被其他用户使用');
        }
      }

      // 更新用户信息
      await user.update({
        nickname: nickname || user.nickname,
        phone: phone || user.phone,
        status: status !== undefined ? status : user.status,
        memberLevel: memberLevel || user.memberLevel,
        avatar: avatar || user.avatar,
        gender: gender || user.gender
      });

      logger.info(`管理员 ${operatorId} 更新了用户 ${userId} 的信息`);

      return user;
    } catch (error) {
      logger.error('Update user failed:', error);
      throw error;
    }
  }

  /**
   * 调整用户积分
   */
  async adjustUserPoints(userId, amount, reason, operatorId) {
    try {
      const user = await User.findByPk(userId);
      
      if (!user) {
        throw new Error('用户不存在');
      }

      // 使用积分服务调整积分
      const result = await pointsService.adjustPoints(userId, amount, {
        type: 'admin_adjust',
        description: reason || '管理员调整',
        operatorId
      });

      logger.info(`管理员 ${operatorId} 为用户 ${userId} 调整积分 ${amount}，原因：${reason}`);

      return result;
    } catch (error) {
      logger.error('Adjust user points failed:', error);
      throw error;
    }
  }

  /**
   * 重置用户密码
   */
  async resetUserPassword(userId, newPassword, operatorId) {
    try {
      const user = await User.findByPk(userId);
      
      if (!user) {
        throw new Error('用户不存在');
      }

      await user.update({ password: newPassword });

      logger.info(`管理员 ${operatorId} 重置了用户 ${userId} 的密码`);

      return true;
    } catch (error) {
      logger.error('Reset user password failed:', error);
      throw error;
    }
  }

  /**
   * 获取用户标签
   */
  async getUserTags(userId) {
    try {
      const user = await User.findByPk(userId);
      
      if (!user) {
        throw new Error('用户不存在');
      }

      const stats = await this.getUserStatistics(userId);
      const tags = [];

      // 根据用户数据生成标签
      if (stats.orderCount === 0) {
        tags.push({ name: '新用户', color: 'blue' });
      } else if (stats.orderCount >= 10) {
        tags.push({ name: '活跃用户', color: 'green' });
      }

      if (stats.totalSpent >= 1000) {
        tags.push({ name: '高价值用户', color: 'gold' });
      }

      if (stats.inviteCount >= 5) {
        tags.push({ name: '推广达人', color: 'purple' });
      }

      if (user.status === 0) {
        tags.push({ name: '已禁用', color: 'red' });
      }

      // 会员等级标签
      const levelTags = {
        'bronze': { name: '铜牌会员', color: 'orange' },
        'silver': { name: '银牌会员', color: 'gray' },
        'gold': { name: '金牌会员', color: 'yellow' },
        'diamond': { name: '钻石会员', color: 'cyan' }
      };

      if (levelTags[user.memberLevel]) {
        tags.push(levelTags[user.memberLevel]);
      }

      return tags;
    } catch (error) {
      logger.error('Get user tags failed:', error);
      throw error;
    }
  }

  /**
   * 用户分群分析
   */
  async getUserSegmentation() {
    try {
      const [
        totalUsers,
        activeUsers,
        newUsers,
        highValueUsers,
        inactiveUsers
      ] = await Promise.all([
        User.count(),
        User.count({
          include: [{
            model: Order,
            where: {
              createdAt: {
                [Op.gte]: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // 30天内
              }
            },
            required: true
          }]
        }),
        User.count({
          where: {
            createdAt: {
              [Op.gte]: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) // 7天内注册
            }
          }
        }),
        User.count({
          include: [{
            model: Order,
            where: {
              status: 'completed'
            },
            required: true,
            having: sequelize.where(
              sequelize.fn('SUM', sequelize.col('Orders.finalAmount')),
              Op.gte,
              1000
            )
          }],
          group: ['User.id']
        }),
        User.count({
          where: {
            lastLogin: {
              [Op.lt]: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // 30天未登录
            }
          }
        })
      ]);

      // 会员等级分布
      const memberLevelDistribution = await User.findAll({
        attributes: [
          'memberLevel',
          [sequelize.fn('COUNT', sequelize.col('id')), 'count']
        ],
        group: ['memberLevel']
      });

      return {
        totalUsers,
        activeUsers,
        newUsers,
        highValueUsers: Array.isArray(highValueUsers) ? highValueUsers.length : 0,
        inactiveUsers,
        memberLevelDistribution: memberLevelDistribution.map(item => ({
          level: item.memberLevel,
          count: parseInt(item.dataValues.count)
        }))
      };
    } catch (error) {
      logger.error('Get user segmentation failed:', error);
      throw error;
    }
  }

  /**
   * 用户行为分析
   */
  async getUserBehaviorAnalysis(userId, days = 30) {
    try {
      const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);

      const [
        loginHistory,
        orderHistory,
        pointsHistory
      ] = await Promise.all([
        // 登录历史（这里需要有登录日志表，暂时用用户更新时间代替）
        User.findByPk(userId, {
          attributes: ['lastLogin']
        }),
        
        // 订单历史
        Order.findAll({
          where: {
            userId,
            createdAt: { [Op.gte]: startDate }
          },
          attributes: ['id', 'status', 'totalAmount', 'createdAt'],
          order: [['createdAt', 'ASC']]
        }),

        // 积分历史
        PointsTransaction.findAll({
          where: {
            userId,
            createdAt: { [Op.gte]: startDate }
          },
          attributes: ['id', 'type', 'amount', 'source', 'createdAt'],
          order: [['createdAt', 'ASC']]
        })
      ]);

      return {
        loginHistory,
        orderHistory,
        pointsHistory
      };
    } catch (error) {
      logger.error('Get user behavior analysis failed:', error);
      throw error;
    }
  }

  /**
   * 批量操作用户
   */
  async batchUpdateUsers(userIds, updateData, operatorId) {
    const transaction = await sequelize.transaction();
    
    try {
      const { status, memberLevel } = updateData;
      const updateFields = {};

      if (status !== undefined) {
        updateFields.status = status;
      }

      if (memberLevel) {
        updateFields.memberLevel = memberLevel;
      }

      await User.update(updateFields, {
        where: {
          id: { [Op.in]: userIds }
        },
        transaction
      });

      await transaction.commit();

      logger.info(`管理员 ${operatorId} 批量更新了 ${userIds.length} 个用户`);

      return true;
    } catch (error) {
      await transaction.rollback();
      logger.error('Batch update users failed:', error);
      throw error;
    }
  }

  /**
   * 导出用户数据
   */
  async exportUsers(options = {}) {
    try {
      const {
        search,
        status,
        memberLevel,
        startDate,
        endDate
      } = options;

      const where = {};
      
      if (search) {
        where[Op.or] = [
          { phone: { [Op.like]: `%${search}%` } },
          { nickname: { [Op.like]: `%${search}%` } }
        ];
      }

      if (status !== undefined) {
        where.status = parseInt(status);
      }

      if (memberLevel) {
        where.memberLevel = memberLevel;
      }

      if (startDate || endDate) {
        where.createdAt = {};
        if (startDate) {
          where.createdAt[Op.gte] = new Date(startDate);
        }
        if (endDate) {
          where.createdAt[Op.lte] = new Date(endDate);
        }
      }

      const users = await User.findAll({
        where,
        attributes: [
          'id', 'phone', 'nickname', 'gender', 'points', 
          'memberLevel', 'invitationCode', 'status', 'createdAt'
        ],
        include: [
          {
            model: User,
            as: 'inviter',
            attributes: ['nickname', 'phone']
          }
        ],
        order: [['createdAt', 'DESC']]
      });

      // 格式化导出数据
      const exportData = users.map(user => ({
        ID: user.id,
        手机号: user.phone || '',
        昵称: user.nickname || '',
        性别: user.gender === 'male' ? '男' : user.gender === 'female' ? '女' : '未知',
        积分: user.points,
        会员等级: user.memberLevel,
        邀请码: user.invitationCode,
        状态: user.status === 1 ? '正常' : '禁用',
        邀请人: user.inviter ? user.inviter.nickname : '',
        注册时间: user.createdAt
      }));

      return exportData;
    } catch (error) {
      logger.error('Export users failed:', error);
      throw error;
    }
  }
}

module.exports = new UserManagementService();